package ProjectTeam39.Networking;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

//	private Presenter presenter;
	
	 /** the socket for the server connect */
    private Socket mySocket;

    /** our output stream on the socket, note that we are
     *  sending objects
     */
    private ObjectOutputStream outStream;

    /** The input stream to get back objects */
    private ObjectInputStream inStream;

    /** the hostname of the server */
    private String host;

    /** the port number of the surver */
    private int port;
    
    public Client(final String hostName, final int portNumber){
    	
    	this.host = hostName;
    	this.port = portNumber;
    	//presenter = new Presenter(hostName, port);
    }
    
    public void connect() {
        try {
            mySocket = new Socket(host, port);
        } catch (UnknownHostException e) {
            System.err.println("Could not find host " + host);
           e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Other failure on connect");
            e.printStackTrace();
        }
    }
    
    public void getStreams(){
    	try{
    		outStream = new ObjectOutputStream(mySocket.getOutputStream());
    		outStream.flush();
    		inStream = new ObjectInputStream(mySocket.getInputStream());
    		System.err.println("Made client instream");
    	}
    	catch (IOException e){
    		System.err.println("Error in getting streams");
            e.printStackTrace();
    	}
    }
    public void send(Message msg){
    	try{
    		outStream.writeUnshared(msg);
    		System.err.println("Sent client message");
    	}
    	catch(IOException e){
    		System.err.println("Error in writing to the output stream");
            e.printStackTrace();
    	}
    }
    public Message receive(){
            Message result = null;
            try {
                result = (Message) inStream.readUnshared();
                System.err.println("Got client message");
            }
            catch (IOException e) {
                System.err.println("Error in reading line");
    	    }
            catch (ClassNotFoundException e) {
                System.err.println("Error in class cast in check method");
            }
            return result;
    }
    
    public void shutdown() {
        try {
        	Message m = new QuitMessage(null);
        	this.send(m);
            inStream.close();
            outStream.close();
            mySocket.close();
        } catch (IOException ioe) {
            System.err.println("Error in closing sockets");
        }
    }

    
/*    public static void main(String[] args){
    	Client c = new Client("host", 45678);
    	try {
    		c.run();
    	}
    	catch(IOException e){
    		e.printStackTrace();
    	}   	
    }
*/
}
